package gupao.concurrency.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

public class Test {
    public class TaskA implements Callable<String> {

        private final Integer splitCount;

        private final ExecutorService executor;

        public TaskA(Integer splitCount, ExecutorService executor) {
            this.splitCount = splitCount;
            this.executor = executor;
        }

        @Override
        public String call() throws Exception {
            //Step1:
            String result1 = step1();
            //Step2:
            List<Future<String>> futureList = new ArrayList<>();
            int count = splitCount;
            while(count-- > 0){
                String param = String.valueOf(count);
                //taskB:
                Future<String> submit = executor.submit(() -> " {Step2:".concat(param).concat("} "));
                //收集结果
                futureList.add(submit);
            }
            List<String> resultList = new ArrayList<>();
            futureList.forEach((future) -> {
                String futureResult = null;
                try {
                    futureResult = future.get();
                } catch (Exception e) {
                    futureResult = "";
                }
                resultList.add(futureResult);
            });
            String result2 = resultList.stream().collect(Collectors.joining());
            //Step3:
            String result3 = step3();
            return result1 + result2 + result3;
        }

        public String step1(){
            return "Step1";
        }

        public String step3(){
            return "Step3";
        }
    }
}
